<template>
  <div class="form-serviceterm">
    <div class="btn-group">
      <!-- start 添加按钮 -->
      <el-button
        type="text"
        size="medium"
        v-if="!isPaySuccess && !onlyFromServiceItem"
        @click="showServiceItmWindow"
      >{{$t('common.base.addModule', {module:''})}}</el-button>
      <!-- end 添加按钮 -->

      <!-- start 从服务清单中添加按钮 -->
      <el-button
        type="text"
        size="medium"
        v-if="!isPaySuccess && isTaskServiceList && serviceList.length > 0"
        @click="openServiceListDialog"
      >{{$t('common.form.preview.serviceItem.btn1')}}</el-button>
      <!-- end 从服务清单中添加按钮 -->
    </div>

    <!-- start 备件列表 -->
    <el-table
      v-if="value.length"
      header-row-class-name="base-table-header-v3"
      row-class-name="base-table-row-v3"
      :data="value"
      border>
      <el-table-column
        v-for="(column, index) in colums"
        :key="`${column.field}_${index}`"
        :label="column.label"
        :prop="column.field"
        show-overflow-tooltip
        :min-width="columsWidth(column)"
        :fixed="column.fixed"
        >
        <template slot-scope="scope">
          <!-- start 数量 -->
          <template v-if="column.field === 'number' && !isPaySuccess">
            <input class="service-number-input" type="number" v-model="scope.row.number" @change="handleServiceItermNum(scope.row)" />
          </template>
          <!-- end 数量 -->

          <!-- start 单价 -->
          <template v-else-if="column.field === 'salePrice'">
            <div v-if='allowEditPrice' :class="internationalGray && allowEditPrice ? 'sale-price-international': ''">
              <input :class="internationalGray ? 'sale-price-edit' : 'service-number-input'" type="number" v-model="scope.row.salePrice" @change="handlePrice(scope.row)" /> 
              <el-select v-if="internationalGray" class='sale-price-select' v-model="scope.row.salePriceCurrency" @change="salePriceCurrencyChange(scope.row)" :placeholder="$t('common.placeholder.select')">
                <el-option
                  v-for="item in currencyOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  >
                </el-option>
              </el-select>
            </div>
            <div v-else>
              {{ scope.row | fmt_salePrice_currency }}
            </div>
          </template>
          <!-- end 单价 -->

          <!-- start 折扣费用 -->
          <template v-else-if="column.field === 'reductionFee' && isServiceItemDiscountSettings">
            {{ getReductionFeeVal(scope.row) }}
          </template>
          <!-- end 折扣费用 -->

          <!-- start 汇率换算方式 -->
          <template v-else-if="column.field === 'exchangeMethod'">
            <el-select v-if="scope.row.salePriceCurrency !== totalCurrency" v-model="scope.row.exchangeMethod" @change="exchangeMethodChange(scope.row, scope.$index)" :placeholder="$t('common.placeholder.select')">
              <el-option
                v-for="item in exchangeMethodsOption"
                :key="item.value"
                :label="item.text"
                :value="item.value"
                >
              </el-option>
            </el-select>
            <div v-else>-</div>
          </template>
          <!-- end 汇率换算方式 -->

          <!-- start 汇率 -->
          <template v-else-if="column.field === 'exchangeRate'">
            <div v-if="scope.row.salePriceCurrency !== totalCurrency" >
              <input 
                :class="['service-number-input', {'el-error': !scope.row.exchangeRate}]"
                type="number" 
                step="any"
                :disabled="scope.row.exchangeMethod !== 2" 
                v-model="scope.row.exchangeRate" 
                :placeholder="$t('common.placeholder.input2')"
                @change="exchangeRateChange(scope.row, scope.$index)"/>
            </div>
            <div v-else>-</div>
          </template>
          <!-- end 汇率 -->

          <!-- start 换算后单价 -->
          <template v-else-if="column.field === 'conversionPrice'">
            <div v-if='scope.row.salePriceCurrency !== totalCurrency'>
              <span v-if="scope.row.exchangeRate">{{(scope.row.exchangeRate * scope.row.salePrice).toFixed(2) }} {{totalCurrency}}</span>
            </div>
            <div v-else>-</div>
          </template>
          <!-- end 换算后单价 -->

          <!-- start 小计 -->
          <template v-else-if="column.field === 'total'">
            {{ getTotalPrice(scope.row) }}
          </template>
          <!-- end 小计 -->

          <!-- start 操作 -->
          <template v-else-if="column.field === 'action'">
            <el-button class="text-danger" type="text" size="mini" @click="value.splice(scope.$index, 1)">{{$t('common.base.delete')}}</el-button>
          </template>
          <!-- end 操作 -->

          <template v-else>{{ scope.row[column.field] }}</template>
        </template>
      </el-table-column>
    </el-table>
    <!-- end 备件列表 -->

    <!-- start 备件免费提示 -->
    <div v-if="isFreeServiceFee" class="free-service-fee"><i class="iconfont icon-warning-circle-fill"></i>{{$t('common.form.preview.serviceItem.des1')}}</div>
    <!-- start 备件免费提示 -->

    <!-- 添加服务项目弹窗 -->
    <base-window :top="true" :flicker="flickerWindow" :unique="false" size="medium" :show.sync="visible" :title="$t('common.form.preview.serviceItem.title1')" class="form-serviceterm-modal" width="700px" @close="reset">
      <div class="base-modal-content">
        <form-builder :fields="fields" ref="form" :value="serviceitem" @update="update">
          <!-- start 服务项目名称 -->
          <template slot="service" slot-scope="{ field }">
            <form-item :label="field.displayName">
              <biz-form-remote-select
                :field="field"
                v-model="selectedItem"
                :remote-method="searchServiceItem"
                @input="updateServiceItem"
                :placeholder="$t('common.placeholder.select')">
                <div class="service-template-option" slot="option" slot-scope="{ option }">
                  <h3>{{option.name}}</h3>
                  <p>
                    <span>
                      <label>{{$t('common.form.preview.serviceItem.label1')}}</label>
                      <span>{{ option.serialNumber }}</span>
                    </span>
                    <span>
                      <label>{{$t('common.form.preview.serviceItem.label2')}}</label>
                      <span>{{option.unit}}</span>
                    </span>
                    <span>
                      <label>{{$t('common.form.preview.serviceItem.label3')}}</label>
                      <span>{{ option.type }}</span>
                    </span>
                  </p>
                </div>
              </biz-form-remote-select>
            </form-item>
          </template>
          <!-- end 服务项目名称 -->

          <!-- 结算规则 S -->
          <template slot="settlementRules" slot-scope="{ field }">
            <form-item :label="field.displayName" v-if="isShowSettlementRules">
              <form-select
                :placeholder="field.placeholder" 
                :field="field"
                v-model="serviceitem.settlementRulesId"  
                :source="ruleOptions" 
                @update="updateSettlementRules" 
                :clearable="false"/>
            </form-item>
          </template>
          <!-- 结算规则 E -->

          <!-- 质保状态 -->
          <template slot="serviceQualityStatus" slot-scope="{ field, value }">
            <form-item :label="field.displayName" v-if="isQualityStatus">
              <form-text :field="field" :value="value" />
            </form-item>
          </template>
          <!-- 质保状态 -->

          <!-- start 单价 -->
          <template slot="salePrice" slot-scope="{ field, value }">
            <form-item :label="field.displayName">
              <div class='sale-price'>
                <form-number :field="field" :value="value" />
                <!-- TODO 需要加国际化判断 -->
                <form-text v-if="internationalGray" :field='currencyField' class='sale-price-currency' :value="serviceitem.salePriceCurrency" />
              </div>
            </form-item>
          </template>
          <!-- end 单价 -->

          <!-- start 小计 -->
          <template slot="total" slot-scope="{ field }">
            <form-item :label="field.displayName">
              <div class='sale-price'>
                <form-text :field="field" :value="total" />
                <!-- TODO 需要加国际化判断 -->
                <form-text v-if="internationalGray" :field='currencyField' class='sale-price-currency' :value="serviceitem.salePriceCurrency" />
              </div>
            </form-item>
          </template>
          <!-- end 小计 -->
        </form-builder>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelWindow">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="submit">{{$t('common.base.save')}}</el-button>
      </div>
    </base-window>

    <service-list-dialog ref="serviceListDialog" :value="value" :data="serviceList" :fields="serviceFields" :totalCurrency="totalCurrency" @submit="addServiceFromList" :taskId="taskId" :isShowSettlementRules="isShowSettlementRules" :ruleOptions="ruleOptions" :onlyFromServiceItem="onlyFromServiceItem"/>
  </div>
</template>

<script>
/* mixin */
import FormMixin from '@src/component/form/mixin/form';
import TaskReceiptMixin from '@src/component/form/mixin/taskReceipt';
/* components */
import ServiceListDialog from './components/ServiceListDialog';
/* util */
import MathUtil from '@src/util/math';
import decode from 'entity-decode';
import * as math from 'mathjs';
import NP from 'number-precision';
/* model */
import { PART_SERVICE_LIST_PRENUM_MAX_LENGTH } from '@src/model/const/Number';
import { PART_SERVICE_LIST_PRENUM_MAX_LENGTH_MESSAGE } from '@src/model/const/Alert';
import { getRootWindow } from '@src/util/dom';

import { getCustomerArrdess } from '@src/filter/fmt.js';
/* api */
import * as TaskApi from '@src/api/TaskApi.ts';
import { currencyOption, exchangeMethodsOption } from '@src/util/currency'
import { serviceFields, currencyField } from './serviceFields.js'
import _ from 'lodash';
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage()
export default {
  name: 'form-serviceterm',
  mixins: [FormMixin, TaskReceiptMixin],
  props: {
    field: {
      type: Object,
      default: () => ({})
    },
    value: {
      type: Array,
      default: () => ([])
    },
    serviceQualityStatus: {
      type: String,
      default: ''
    },
    // 工单结算规则数据
    settlementRulesList: {
      type: Object,
      default: () => ({})
    },
    taskId: {
      type: String,
      default: ''
    },
    /**工单关联产品ids */
    productIds: {
      type: Array,
      default: () => ([])
    },
  },
  inject: ['fetchRuleList', 'initData'],
  data() {
    return {
      visible: false,
      selectedItem: [], // 当前选中的服务项目
      serviceitem: this.initServiceData(), // 服务项目信息
      editUnitPrice: false, // 是否可以修改单品价格
      isPaySuccess: false, // 是否支付成功
      serviceList: [], // 服务项目清单
      serviceFields: [], // 服务清单字段
      // 窗口是否闪烁
      flickerWindow: false,
      isFreeServiceFee: false,
      task: this.initData.task,
      currencyOption,
      currencyField,
      exchangeMethodsOption,
      internationalGray
    }
  },
  watch:{
    value:{
      handler(){
        this.handleDiscountPrice();
      },
      immediate:true,
    },
  },
  computed: {
    // 是否仅展示关联产品的服务项目内容
    onlyShowRelatedServiceItem() {
      return this.field?.setting?.onlyShowRelatedServiceItem || false;
    },
    // 仅可从服务清单中添加
    onlyFromServiceItem() {
      return this.field?.setting?.onlyFromServiceItem || false
    },
    ruleOptions() {
      const { serviceIterm } = this.settlementRulesList;

      return (serviceIterm || [])
      .map(item => {
        return {
          text: item.ruleName,
          value: item.id,
          ...item,
          attribute: item?.attribute ? JSON.parse(item?.attribute) : {}
        }
      }).filter(item => {
        let qualityStatus = this.$t('common.base.surrender')
        if (item.attribute.qualityStatus == 'IN' || item.attribute.qualityStatusName == '保内') {
          qualityStatus = this.$t('common.base.warranty')
        }
        return this.serviceQualityStatus ? (qualityStatus === this.serviceQualityStatus) : item
      })
    },
    // 服务清单灰度
    isTaskServiceList() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.taskServiceList || false
    },
    // 结算规则灰度
    isSettlementRule() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.settlementRule || false
    }, 

    // 服务项目折扣灰度
    isServiceItemDiscountSettings() {
      const RootWindow = getRootWindow(window)
      return Boolean(RootWindow.grayAuth?.serviceItemDiscountSettings)
    },
    // 是否显示结算规则
    isShowSettlementRules() {
      return !!this.ruleOptions.length && this.isSettlementRule
    },
    /**
    * @description 服务项目列表项
    */
    colums() {
      let colums = [{
        label: this.$t('common.form.preview.serviceItem.colum1'),
        field: 'name'
      }, 
      {
        label: this.$t('common.form.preview.serviceItem.colum2'),
        field: 'serialNumber'
      },{
        label: this.$t('common.form.preview.serviceItem.colum3'),
        field: 'type'
      }, {
        label: this.$t('common.form.preview.serviceItem.colum4'),
        field: 'unit'
      }, {
        label: this.$t('common.form.preview.serviceItem.colum5'),
        field: 'number',
      },{
        label: this.$t('common.form.preview.serviceItem.colum6'),
        field: 'salePrice',
        minWidth: '120px'
      }, {
        label: this.$t('common.form.preview.serviceItem.colum7'),
        field: 'total',
        fixed: 'right'
      }]

      if (this.isShowSettlementRules) {
        colums.splice(2, 0, {
          label: this.$t('common.zhongqi.title1'),
          field: 'settlementRules',
        },
        {
          label: this.$t('common.form.preview.qualityField.label3'),
          field: 'serviceQualityStatus'
        })
      }
      // 支付成功前可编辑
      if (!this.isPaySuccess) {
        colums.push({
          label: this.$t('common.base.operation'),
          field: 'action',
          minWidth: '70px',
          fixed: 'right'
        })
      }
      // 国际化灰度开启
      if (this.internationalGray) {
        colums.splice(colums.length-2, 0, {
          label: this.$t('common.currency.exchangeMethod'),
          field: 'exchangeMethod',
          minWidth: '140px'
        },
        {
          label: this.$t('common.currency.exchangeRate'),
          field: 'exchangeRate',
          minWidth: '130px'
        },
        {
          label: this.$t('common.currency.conversionPrice'),
          field: 'conversionPrice',
          minWidth: '100px'
        })
      }

      // 完成回执-服务项目table 是否隐藏单价和小计
      if(!this.serviceProviderShowPrice) {
        colums = colums.filter(column => column.field !== 'salePrice' && column.field !== 'total' && column.field !== 'conversionPrice')
      }

      // 服务项目折扣相关灰度
      if(this.isServiceItemDiscountSettings){
        // 先找到单价的下标，找到后再在其后面拼折扣费用
        colums.forEach((item,index) => {
          if(item.field === 'salePrice'){
            colums.splice(index + 1, 0, {
              label: this.$t('kaili.list.reductionFee'),
              field: 'reductionFee',
            })
          }
        })
      }

      return colums;
    }, 
    fields() {
      // TODO-bdz 表单可能存在逻辑
      let fields = [{
        formType: 'select',
        fieldName: 'service',
        displayName: this.$t('common.form.preview.serviceItem.colum1'),
        placeholder: this.$t('common.placeholder.select'),
        isNull: 0,
      }, {
        formType: 'select',
        fieldName: 'settlementRules',
        displayName: this.$t('common.zhongqi.title1'),
        placeholder: this.$t('zhongqi.tipList.tips1'),
        isNull: 0,
      }, {
        formType: 'text',
        fieldName: 'serialNumber',
        displayName: this.$t('common.form.preview.serviceItem.colum2'),
        isNull: 1,
        disabled: true
      }, 
      {
        formType: 'text',
        fieldName: 'serviceQualityStatus',
        displayName: this.$t('zhongqi.setting.warrantyStatus'),
        isNull: 1,
        disabled: true
      },
      {
        formType: 'text',
        fieldName: 'type',
        displayName: this.$t('common.form.preview.serviceItem.colum3'),
        placeholder: ' ',
        isNull: 1,
        disabled: true
      }, {
        formType: 'text',
        fieldName: 'unit',
        displayName: this.$t('common.form.preview.serviceItem.colum4'),
        isNull: 1,
        disabled: true
      }, {
        formType: 'text',
        fieldName: 'salePrice',
        displayName: this.$t('common.form.preview.serviceItem.colum6'),
        isNull: 1,
        disabled: true
      }, {
        formType: 'number',
        fieldName: 'number',
        displayName: this.$t('common.form.preview.serviceItem.colum5'),
        isNull: 0,
      }, {
        formType: 'text',
        fieldName: 'total',
        displayName: this.$t('common.form.preview.serviceItem.colum7'),
        isNull: 1,
        disabled: true
      }];

      // 完成回执-添加服务项目 是否隐藏单价和小计
      if(!this.serviceProviderShowPrice) {
        fields = fields.filter(field => field.fieldName !== 'salePrice' && field.fieldName !== 'total' && field.fieldName !== 'conversionPrice')
      }

      return fields;
    },
    /**
    * @description 小计
    */
    total() {
      let { number, salePrice } = this.serviceitem;
      return number && salePrice ? (number * salePrice).toFixed(2) : '';
    },
    conversionPrice() {
      let { exchangeRate, salePrice } = this.serviceitem;
      return exchangeRate && salePrice ? (exchangeRate * salePrice).toFixed(2) : '';
    },
    /**
    * @description 允许修改单价
    */
    allowEditPrice() {
      return this.editUnitPrice && !this.isPaySuccess;
    },

    // 是否显示质保状态
    isQualityStatus() {
      return this.serviceQualityStatus && this.isSettlementRule
    },
    // 卡片
    cardTab() {
      return this.initData?.cardInfo || []
    },
    // 服务清单
    servicelistTab() {
      // 先不翻译 - 工单附加组件也是相同的逻辑去值的
      return this.cardTab.find(item => item.specialfrom === '服务清单')
    }
  },
  methods: {
    // 根据数据计算折扣相关价格
    handleDiscountPrice(){
      let newVal = this.value;

      const discountRulesList = this.field.setting?.serviceItemDiscountSettings || [];
      if (!newVal.length || !this.isServiceItemDiscountSettings) return;

      const getPreItemNumber = (index) => {
        if (index == 0) return newVal[0].num || newVal[0].number
        let num = 0
        for (let i = 0; i < index; i++) {
          num += Number(newVal[i].num || newVal[i].number)
        }
        return num
      }
      newVal.forEach((item, index) => {
        // 根据 discountRulesList 的配置，动态设置每条数据的折扣
        if(discountRulesList.length){
          let totalValue = 0
          const number = item.num || item.number
          const preItemNum = getPreItemNumber(index)
          for (let i = 0; i < number; i++) {
            // 折扣逻辑：比如第一行数量为5，则取配置的1-5行折扣数据，第二行数量为3，则取配置的6-8行折扣数据，以此类推
            // 当前行折扣，没有数据默认0
            let discount = 0
            if (index == 0) {
              discount = discountRulesList[i]?.index || 0
            } else {
              discount = discountRulesList[preItemNum + i]?.index || 0
            }
            // 小计 += 单价 * (1 - 每一行折扣 / 100)
            // 加减乘除 .plus .minus .times .divide
            totalValue = NP.plus(totalValue, NP.times(item.salePrice, NP.minus(1, NP.divide(discount, 100))).toFixed(2))
          }
          // 折扣费用 = 单价 * 数量 - 小计
          const reductionFeeValue = NP.minus(NP.times(item.salePrice, item.number), totalValue).toFixed(2)

          this.$set(item, 'total', totalValue )
          this.$set(item, 'reductionFee', reductionFeeValue )
        }
      })
    },
    // 折扣费用
    getReductionFeeVal(item){
      const reductionFee = item.reductionFee ? item.reductionFee: 0
      // 国际化灰度
      if(internationalGray) {
        return `${reductionFee} ${this.totalCurrency}`
      }
      return reductionFee
    },
    columsWidth(column) {
      if(column.field == 'salePrice' && internationalGray && this.allowEditPrice) return '200px'
      return column.minWidth || '108px'
    },
    getTotalPrice(item){
      let { number, salePrice, exchangeRate, salePriceCurrency } = item

      const totalPrice = item.total ? item.total : 0
      // 服务项目折扣灰度 + 国际化灰度
      if(this.isServiceItemDiscountSettings && internationalGray){
        return `${totalPrice} ${this.totalCurrency}`
      }

      // 服务项目折扣灰度
      if(this.isServiceItemDiscountSettings){
        return totalPrice
      }
      // 国际化灰度
      if(internationalGray) {
        if(exchangeRate) {
          let price = (number * salePrice * exchangeRate).toFixed(2)
          return `${price} ${this.totalCurrency}`
        }else {
          return ''
        }
      }
      return (number * salePrice).toFixed(2)
    },
    /**
    * @description 初始化服务项目默认值
    */
    initServiceData() {
      return {
        id: '',
        name: '',
        serialNumber: '',
        type: '',
        salePrice: '',
        costPrice: '',
        number: '',
        unit: '',
        settlementRules: '',
        settlementRulesId: '',
        isFree: '',
        isFreeName: '',
        qualityStatus: '',
        serviceQualityStatus: this.serviceQualityStatus,
        exchangeRate: '',
        exchangeMethod: 1,
        salePriceCurrency: 'CNY',
        costPriceCurrency: "CNY"
      }
    },
    /**
    * @description 修改列表服务项目数量
    */
    handleServiceItermNum(item) {
      let value = Number(item.number);
      let count = MathUtil.decimalNumber(value); // 小数位数

      if (value <= 0) {
        this.$platform.alert(this.$t('common.form.preview.materialVerifyEliminate.rightNumTip'));
        item.number = 1;
        this.handleDiscountPrice();
        return;
      }

      let currentService = this.serviceList.find(zitem => zitem.id === item.id);
      let max = (this.onlyFromServiceItem && currentService?.number) ? currentService.number : PART_SERVICE_LIST_PRENUM_MAX_LENGTH;
      if (value > max) {
        this.$platform.alert(this.$t('common.modal.PART_SERVICE_LIST_PRENUM_MAX_LENGTH_MESSAGE', { PART_SERVICE_LIST_PRENUM_MAX_LENGTH: max }));
        item.number = max;
        this.handleDiscountPrice();
        return;
      }

      if (count > 2) {
        this.$platform.alert(this.$t('common.form.tip.materialReturn.tips9'));
        item.number = 1;
        this.handleDiscountPrice();
        return;
      }
      this.handleDiscountPrice();
    },
    /**
    * @description 修改列表服务项目单价
    */
    handlePrice(item) {
      let value = Number(item.salePrice);
      let count = MathUtil.decimalNumber(value);
      let oldPrice = item.oldPrice ? item.oldPrice : 0;

      if(value < 0){
        this.$platform.alert(this.$t('common.base.tip.inputNumberMoreThan', {data1:0}));
        item.salePrice = oldPrice;
        this.handleDiscountPrice();
        return;
      }

      if(count > 2) {
        this.$platform.alert(this.$t('common.form.tip.materialReturn.tips9'));
        item.salePrice = oldPrice;
        this.handleDiscountPrice();
        return;
      }
      this.handleDiscountPrice();
    },
    /**
    * @description 弹窗关闭重置数据
    */
    reset() {
      this.serviceitem = this.initServiceData();
      this.selectedItem = [];
      // 清空校验结果
      this.$refs.form.$children.map(child => {
        if (child.$el.className == 'form-item err') {
          child.$el.dispatchEvent(new CustomEvent('form.clear.validate', {bubbles: false}));
        }
      })
    },
    /**
    * @description 更新表单数据
    */
    update({field, newValue, oldValue}) {
      let {fieldName, displayName} = field;
      if (this.$appConfig.debug) {
        console.info(`[FormBuilder] => ${displayName}(${fieldName}) : ${JSON.stringify(newValue)}`);
      }
      this.$set(this.serviceitem, fieldName, newValue);
    },
    /**
    * @description 搜索服务项目
    */
    searchServiceItem(params) {
      // params has three properties include keyword、pageSize、pageNum.
      // 工单回执添加服务项目时，默认将该产品的产品类型所关联的服务项目靠前展示，非关联的服务靠后展示
      // 如果工单关联了多个产品时，那么根据产品的顺序依次展示关联的服务项目的顺序
      const pms = {
        ...params,
        taskId: this.task.id,
        needAreaPrice: this.field?.setting?.useRegionalPricing || false,
        address: getCustomerArrdess(this.task)
      }
      // 开启展示关联产品的服务项目内容
      if(this.onlyShowRelatedServiceItem) { 
        pms.productIds = this.productIds
      }

      return this.$http
        .post('/task/service/list', pms)
        .then(res => {
          let isFreeServiceFee = JSON.parse(sessionStorage.getItem('isFreeServiceFee'))
          if (!res || !res.list) return;   
          if (isFreeServiceFee) {
            res.list.forEach(item => {
              item.salePrice = 0;
            })
          }   
          res.list = res.list.map(template =>
            Object.freeze({
              label: decode(template.name),
              value: template.id,
              ...template,
              name: decode(template.name)
            })
          )   
          return res;
        })
        .catch(e => console.error(e));
    },
    /**
    * @description 选择服务项目
    */
    updateServiceItem(value) {

      let newValue = value[0];

      for (let key in this.serviceitem) {
        if (key == 'salePrice') {
          this.serviceitem.salePrice = newValue.salePrice.toFixed(2);
        } else if (key == 'number') {
          this.serviceitem.number = 1;
        } else if (key == 'serviceQualityStatus') {
          // 产品质保不做清空
          this.serviceitem.serviceQualityStatus = this.serviceQualityStatus;
        }else if(key == 'salePriceCurrency') {
          this.serviceitem.salePriceCurrency = newValue.salePriceCurrency || 'CNY';
        }
        else {
          this.serviceitem[key] = newValue[key];
        }
      }
      if(internationalGray) {
        this.setCurrenyKey(this.serviceitem, this.serviceitem.salePriceCurrency)
      }
    },
    // 更新结算规则
    updateSettlementRules({ newValue }) {
      let selectRuleArr = this.ruleOptions.filter(item => {
        return item.value == newValue
      })
      this.serviceitem['isFree'] = selectRuleArr[0]?.attribute?.isFree || '';
      this.serviceitem['isFreeName'] = selectRuleArr[0]?.attribute?.isFreeName || '';
      this.serviceitem['settlementRules'] = selectRuleArr[0]?.ruleName || '';
      this.serviceitem['qualityStatus'] = selectRuleArr[0]?.attribute?.qualityStatus || '';
      this.serviceitem['settlementRulesId'] = newValue;
    },
    /**
    * @description 数量校验
    */
    validateNumber(value, field){
      // 小数位数
      let count = MathUtil.decimalNumber(value);

      return new Promise((resolve, reject) => {
        if(Number(value) <= 0) {
          return resolve(this.$t('common.form.preview.materialVerifyEliminate.rightNumTip'));
        }

        if(Number(value) > PART_SERVICE_LIST_PRENUM_MAX_LENGTH) {
          return resolve(PART_SERVICE_LIST_PRENUM_MAX_LENGTH_MESSAGE);
        }

        if (count > 2) {
          return resolve(this.$t('common.form.tip.materialReturn.tips9'));
        }
        resolve(null);
      })
    },
    /**
    * @description 添加服务项目
    */
    async submit() {
      try {
        const validateRes = await this.$refs.form.validate();
        if (!validateRes) return;

        let serviceObj = JSON.parse(JSON.stringify(this.serviceitem));
        serviceObj.oldPrice = serviceObj.salePrice;

        let newValue = this.value;

        // 查找已添加的服务项目中是否存在该服务项目
        let ids = newValue.findIndex(val => val.id == serviceObj.id && val.salePrice == serviceObj.salePrice);

        if (ids > -1) {
          newValue[ids].number = Number(math.add(math.bignumber(newValue[ids].number), serviceObj.number));
        } else {
          // TODO 国际化灰度开启
          if(internationalGray) {
            serviceObj.oldPriceCurrency = serviceObj.salePriceCurrency;
            this.setCurrenyKey(serviceObj, serviceObj.salePriceCurrency)
            serviceObj.exchangeMethod = 1
          }
          newValue.push(serviceObj);
        }
        this.$emit('update', {field: this.field, newValue});

        this.visible = false;

      } catch (e) {
        console.error('err', e);
      }
    },
    setEditConfig(config) {
      let { editUnitPrice, isPaySuccess, serviceList, serviceFields } = config || {};

      // 完成回执-从服务清单中添加 是否隐藏单价和小计
      if(!this.serviceProviderShowPrice) {
        serviceFields = serviceFields.filter(column => column.fieldName !== 'salePrice' && column.fieldName !== 'total' &&  column.fieldName !== 'conversionPrice')
      }

      this.editUnitPrice = editUnitPrice;
      this.isPaySuccess = isPaySuccess;
      this.serviceFields = serviceFields;

      // 服务清单添加质保状态字段 灰度开启的情况下
      if (this.isSettlementRule) {
        this.serviceFields.forEach((item) => {
          item.serviceQualityStatus = this.serviceQualityStatus
        })
      }
    },
    openServiceListDialog() {
      this.$refs.serviceListDialog.open();
      // 重新请求接口，因为数据不是最新的
      this.$refs.serviceListDialog && this.getInventoryByCardId();
      // 调用接口，重新获取规则的下拉数据，防止数据没有及时更新
      this.fetchRuleList();
    },
    /** 
    * @description 查询服务清单列表数据
    */
    async getInventoryByCardId() {
      this.$refs.serviceListDialog.listLoading = true;
      try {
        const params = {
          cardId: this.servicelistTab?.cardId,
          taskId: this.task?.id,
          needAreaPrice: this.field?.setting?.useRegionalPricing || false,
          address: getCustomerArrdess(this.task)
        }
        let res = await TaskApi.getInventoryByCardId(params);
        if (!res.success || !res.result) return;

        this.serviceList = (res.result || []).map(item => {
          return {
              ...item,
              id: item.relatedId,
              number: item.preNum,
              type: item.sparepartType
          }
        })

      } catch(err) {
        console.error('service getInventoryByCardId err', err)
      } finally {
        this.$refs.serviceListDialog.listLoading = false;
      }
    },
    /**
    * @description 从清单中添加服务项目
    */
    addServiceFromList(data) {
      let newValue = data.map(item => {
        let serviceItem = {};
        for (let key in this.serviceitem) {
          serviceItem[key] = item[key];
        }
        if(internationalGray) {
          let salePriceCurrency = item.salePriceCurrency ? item.salePriceCurrency : 'CNY'
          serviceItem.salePriceCurrency = salePriceCurrency
          serviceItem.oldPriceCurrency = salePriceCurrency;
        }
        serviceItem.serviceQualityStatus = this.serviceQualityStatus;
        serviceItem.oldPrice = serviceItem.salePrice;
        return serviceItem;
      })

      this.$emit('update', {field: this.field, newValue});
    },
    showServiceItmWindow() {
      // 调用接口，重新获取规则的下拉数据，防止数据没有及时更新
      this.fetchRuleList();

      if (!this.visible) {
        return this.visible = true
      }

      this.flickerWindow = true
      this.$nextTick(() => {
        this.flickerWindow = false
      })
    },
    cancelWindow() {
      this.visible = false
      this.flickerWindow = false
    }
  },
  mounted() {
    this.$eventBus.$on('task_receipt_update_config', this.setEditConfig); 
    this.isFreeServiceFee = JSON.parse(sessionStorage.getItem('isFreeServiceFee'))
    this.getInventoryByCardId();
  },
  beforeDestroy() {
    this.$eventBus.$off('task_receipt_update_config', this.setEditConfig);
  },
  components: {
    [ServiceListDialog.name]: ServiceListDialog
  }
}
</script>

<style lang="scss">
.form-item.err :not(.is-success){
  .form-item :not(.err) {
    input, .base-select-main-content {
      border-color: #e0e1e2 !important;
    }
  }

  .form-item.err {
    input, .base-select-main-content {
      border-color: #f56c6c !important;
    }
  }
}

.form-serviceterm {
  text-align: left;

  .btn-group {
    padding: 0 !important;

    .el-button {
      min-width: auto !important;
      padding: 8px 0 0 0;
    }
  }

  .el-table {
    margin: 10px 0;
    .sale-price-international {
      width: 200px
    }
    .service-number-input {
      width: 99%;
    }
    .el-error {
      border: 1px solid #f56c6c
    }
    .sale-price-edit {
      width: 40%;
    }
    .sale-price-select {
      width: 55%;
      margin-left: 5px;
    }
    .el-icon-delete {
      font-size: 16px;
      color: $color-danger;
      font-weight: 700;
    }
  }
}

.service-template-option {
  * {
    margin: 0;
  }
  padding: 10px 0;
  h3 {
    font-size: 14px;
    font-weight: 500;
    line-height: 24px;
  }

  p {
    display: flex;
    justify-content: space-between;
    line-height: 24px;

    & > span {
      width: 50%;
      display: flex;
      justify-content: flex-start;
      font-size: 12px;
      color: #666666;
      padding-right: 10px;

      & > label {
        padding: 0;
        width: auto !important;
      }
      & > span {
        @include text-ellipsis();
      }
    }
  }
}
.free-service-fee {
  .iconfont {
    color: #FAAD14;
    margin-right: 8px;
  }
}
.sale-price {
  display: flex;
  .sale-price-currency {
    width: 20%;
    margin-left: 5px
  }
}
</style>
